﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AteneoLibriBusinessLogic.Entities;

namespace AteneoLibri.Utility
{
    public class HttpSessionManager
    {
        public static void Clear()
        {
            HttpSessionManager._checkHttpContext();
            System.Web.HttpContext.Current.Session.Clear();
            System.Web.HttpContext.Current.Session.Abandon();
        }

        private static bool _checkHttpContext()
        {
            if (System.Web.HttpContext.Current != null)
                return true;
            else
                throw new Exception("Empty HttpContext.");
        }

        public static void SetWebUser(User webUser)
        {
            HttpSessionManager._checkHttpContext();
            System.Web.HttpContext.Current.Session["AteneoLibri.Session.User"] = webUser;
        }

        public static User GetWebUser()
        {
            HttpSessionManager._checkHttpContext();
            User user = null;
            try
            {
                if (System.Web.HttpContext.Current.Session["AteneoLibri.Session.User"] != null)
                    user = (User)System.Web.HttpContext.Current.Session["AteneoLibri.Session.User"];                
            }
            catch (Exception)
            {
                Clear();
            }
            return user;
        }

        public static void ClearWebUser(HttpContext context, User webUser)
        {
            context.Session["AteneoLibri.Session.User"] = null;
        }
    }
}